<template>
  <transition name="fade">
    <div class="modal" v-show="show" @mousemove="modalMove" @mouseup="cancelMove">
      <div class="container">
        <div class="header" @mousedown="setStartingPoint">
          <div class="cancel" @click="cancelModal">×</div>
          {{title}}
        </div>
        <div class="main">
          <slot />
        </div>
        <div class="footer">
          <div @click="cancelModal">取消</div>
          <div @click="submit">提交</div>
        </div>
      </div>
    </div>
  </transition>
</template>

<script>
export default {
  name: 'Modal',
  data () {
    return {
      x: 0,
      y: 0,
      node: null,
      isCanMove: false
    }
  },
  props: {
    show: {
      type: Boolean,
      default: true
    },
    title: {
      type: String,
      default: '弹框标题'
    }
  },
  mounted () {
    this.node = document.querySelector('.container')
  },
  methods: {
    // 记录开始鼠标距离被移动元素左边的距离
    setStartingPoint (e) {
      this.x = e.clientX - this.node.offsetLeft
      this.y = e.clientY - this.node.offsetTop
      this.isCanMove = true
    },
    // 进行移动
    modalMove (e) {
      if (this.isCanMove) {
        this.node.style.left = e.clientX - this.x + 'px'
        this.node.style.top = e.clientY - this.y + 'px'
      }
    },
    // 移动取消
    cancelMove () {
      this.isCanMove = false
    },
    cancelModal () {
      this.$emit('hideModal')
    },
    submit () {
      this.$emit('submit')
    }
  },
}
</script>

<style scoped>
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
.modal {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
}
.container {
  position: fixed;
  width: 500px;
  height: 200px;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background: #fff;
}
.header {
  font-size: 20px;
  font: bold;
  margin: 10px;
  position: relative;
}
.cancel {
  content: "×";
  position: absolute;
  right: 10px;
  top: 10px;
  font-size: 30px;
}
.main {
  padding-left: 20px;
  padding-top: 20px;
}
.footer {
  position: absolute;
  right: 10px;
  bottom: 10px;
  display: flex;
}
.footer div {
  margin-right: 10px;
  cursor: pointer;
  padding: 10px;
}
.footer div:nth-child(2) {
  background: skyblue;
}
/* // 写一点淡入谈出的动画试试 */
/* // 离开前,进入后透明度是1 */
.fade-leave,
.fade-enter-to {
  opacity: 1;
}
/*  //过度时间 */
.fade-leave-active,
.fade-enter-active {
  transition: all 1s;
}
/* 进入前，离开后 */
.fade-leave-to,
.fade-enter {
  opacity: 0;
}
</style>